$(function(){
/* ******************** GLOBAL FUNCTIONS ********************** */
    //affiche la div suivante
    $('.showNextDiv').live("click",function(){
        if($(this).next('div').is(':hidden')){
            $(this).next('div').slideDown();
        }else{
            $(this).next('div').slideUp();
        }
    });

    //side menu navigation
    
    $(".contentMenuItems ul li a").live('click',function(){
        $href=$(this).attr('href');
        $(".contentMenuItems ul li a").removeClass('active');

        $(this).addClass('active');
        //return false;
    });
    
    //hide flash message
    $('.message').delay(5000).fadeOut();

/* ******************** DEMAND FORM FUNCTIONS ********************** */
    var PathPD='/alwpa/Powerdelegations/';//action Powerdelegation
    var PathJp='/alwpa/Jobprofiles/';//action Powerdelegation
    var PathUser='/alwpa/Users/';//action Powerdelegation
    var PathComp='/alwpa/Companies/';//action Powerdelegation

    //Pc Type
    $('#DmdformNeedsPc').live('click',function(){
        if ($('#DmdformNeedsPc').is(':checked')){
		
            $('.pcType').slideDown();
        }else{
            $('.pcType').slideUp();
        }
    });

    //new job function , ajouter nouvelle fonction pas dans la liste
    $('.isNewJobfunction').live('click',function(){
        if ($('.isNewJobfunctionDiv').is(':hidden')){
            $('.isNewJobfunctionDiv').slideDown();
            $('#DmdformIsNewJobfunction').val(1);
            $('#DmdformIsNewJobfunction_').val(1);
        }else{
            $('.isNewJobfunctionDiv').slideUp();
            $('#DmdformIsNewJobfunction').val(0);
            $('#DmdformIsNewJobfunction_').val(0);
            $('#DmdformUserJobfunctionTitle').val("");
        }
    });

    //new job function , ajouter nouvelle fonction pas dans la liste pour BAck Up
    $('.isNewBUJobfunction').live('click',function(){
        if ($('.isNewBUJobfunctionDiv').is(':hidden')){
            $('.isNewBUJobfunctionDiv').slideDown();
            $('#DmdformIsNewBackupJobfunction').val(1);
            $('#DmdformIsNewBackupJobfunction_').val(1);
        }else{
            $('.isNewBUJobfunctionDiv').slideUp();
            $('#DmdformIsNewBackupJobfunction').val(0);
            $('#DmdformIsNewBackupJobfunction_').val(0);
            $('#DmdformBackupJobfunctionTitle').val("");
        }
    });

    //has dmdform for back up
    $('#DmdformBackupCreated').live('change',function(){
        if ($('#DmdformBackupCreated').is(':checked')){
            $('.backupHasDmdForm').slideDown();
        }else{
            $('.backupHasDmdForm').slideUp();
        }
    });

    //has dmdform for manager
    $('#DmdformManagerCreated').live('change',function(){
        if ($('#DmdformManagerCreated').is(':checked')){
            $('.managerHasDmdForm').slideDown();
        }else{
            $('.managerHasDmdForm').slideUp();
        }
    });

    //Ajouter Workflow
    $('.addWorkflow').live('click',function(){
        if ((parseInt($('.wknb').text()))<10){
        $('.wk'+$('.wknb').text()).show();
        $('.wknb').text((parseInt($('.wknb').text())+1));}
        if ((parseInt($('.wknb').text()))>0){$('.removeWorkflow').show();}
        if ((parseInt($('.wknb').text()))==10){$('.addWorkflow').hide();}
    });

    //enlever Workflow
    $('.removeWorkflow').live('click',function(){
        if ((parseInt($('.wknb').text()))>0){
        $('.wk'+(parseInt($('.wknb').text())-1)).hide();
        $('#DmdformUserWorkflowId'+(parseInt($('.wknb').text())-1)).val('');
        $('#DmdformUserPowerdelegationId'+(parseInt($('.wknb').text())-1)).empty();
        $('.wknb').text((parseInt($('.wknb').text())-1));
        if ((parseInt($('.wknb').text()))==0){$('.removeWorkflow').hide();}
        if ((parseInt($('.wknb').text()))<10){$('.addWorkflow').show();}}
    });
/*************************************************************************************************************************/    
    
    
/************************************************************************************************************************
 *   TOOLS
 *************************************************************************************************************************/
    //Ajouter Tool
    $('.addTool').live('click',function(){
        max=parseInt($('.maxNb').text());
        if ((parseInt($('.toolNb').text()))<max ){
        $('.tool'+$('.toolNb').text()).show();
        $('.toolNb').text((parseInt($('.toolNb').text())+1));}
        if ((parseInt($('.toolNb').text()))>0){$('.removeTool').show();}
        if ((parseInt($('.toolNb').text()))==max){$('.addTool').hide();}
    });

    //enlever Tool
    $('.removeTool').live('click',function(){
        max=parseInt($('.maxNb').text());
        if ((parseInt($('.toolNb').text()))>0){
        $('.tool'+(parseInt($('.toolNb').text())-1)).hide();
        $('#DmdformUserToolId'+(parseInt($('.toolNb').text())-1)).val('');
        $('.toolNb').text((parseInt($('.toolNb').text())-1));
        if ((parseInt($('.toolNb').text()))==1){$('.removeTool').hide();}
        if ((parseInt($('.toolNb').text()))<max){$('.addTool').show();}}
    });
    
    //toolList
    
    $('.toolList').live('change',function(){
        //alert($(this).val().length);
         $id=$(this).attr('id').substring($(this).attr('id').length-1);
        if ($(this).val().length!=0) {
      
       $('#toolTables'+$id).val($(this).val());
       //alert($('#toolTables'+$id).val());
       $ttable=$('#toolTables'+$id).find('option:selected').text();
       if ($ttable.length>0){
           $('#toolTableName'+$id).val($ttable);
           $.post('/alwpa/'+$ttable+'/addSpecific',function(data){
               $('#formContainerBtn'+$id).show();
                $('#formContainer'+$id).empty().append(data).slideDown();
                
           });
       }else{
            $('#formContainer'+$id).empty().slideUp();
            $('#formContainerBtn'+$id).hide();
       }}else{
            $('#formContainer'+$id).empty().slideUp();
            $('#formContainerBtn'+$id).hide();
       }
       
    });
    
/*************************************************************************************************************************/
    //populate powerdelegation list according to workflow id
    $('.wkList').live('change',function(){
        pdList=$(this).attr('id').substr($(this).attr('id').length-1,1);
        if($(this).val()>0){
            $(this).parent().parent().append('<div class="fieldLoader"></div>')
            path=PathPD+'populateList/'+$(this).val();
            $.get(path,{},function(data){
                $('#DmdformUserPowerdelegationId'+pdList).html(data);
                $('.fieldLoader').remove();
            });
        }else{
            $('#DmdformUserPowerdelegationId'+(parseInt($('.wknb').text())-1)).empty();
        }
    });
/*************************************************************************************************************************/

    //Users show detail
    $('#DmdformUserId').live('change',function(){
        
        $action=PathUser+'showUser/'+$(this).val();
        $container=$('.showUser');
        if($(this).val().length==0){
            $container.empty().hide();
             $container.parent().find('.showNextDiv').hide();
             if($("#editUser").length>1){
                 $("#editUser").parent().find('.inform').show();
             }
        }else{
        $container.parent().find('.showNextDiv').show();
        $container.empty().append('<div class="fieldLoader"></div>').show();
        $.post($action,function(data){
            $container.empty().append(data);
        });
        if($("#editUser").length>0){
            //alert('e');
           $c=$("#editUser");
           $c.parent().find('.inform').hide();
           $c.append('<div class="loader"></div>');
           $action=PathUser+'editUser/'+$(this).val(); 
           $.post($action,function(data){
                $c.empty().append(data);
                 popBox.init("mybox");
            });
        }
        
        }
    });

    //replace show detail
    $('#DmdformUserReplace').live('change',function(){

        $action=PathUser+'showUser/'+$(this).val();
        $container=$('.showUserReplace');
        if($(this).val().length==0){
            $container.empty().hide();
             $container.parent().find('.showNextDiv').hide();
             $(this).parent().parent().parent().next('tr').show();
        }else{
        $(this).parent().parent().parent().next('tr').hide();
        $container.parent().find('.showNextDiv').show();
        $container.empty().append('<div class="fieldLoader"></div>').show();
        $.post($action,function(data){
            $container.empty().append(data);
        });}
    });

    //backupOf show detail
    $('#DmdformUserBackupOf').live('change',function(){
        $action=PathUser+'showUser/'+$(this).val();
        $container=$('.showUserBackUpOf');
        
        if($(this).val().length==0){
            $container.empty().hide();
             $container.parent().find('.showNextDiv').hide();

              $(this).parent().parent().parent().next('tr').show();
        }else{
             $(this).parent().parent().parent().next('tr').hide();
        $container.parent().find('.showNextDiv').show();
        $container.empty().append('<div class="fieldLoader"></div>').show();
        $.post($action,function(data){
            $container.empty().append(data);
        });}
    });

    //Hrereferent show detail
    $('#DmdformUserHrreferntId').live('change',function(){
        $action=PathUser+'showUser/'+$(this).val();
        $container=$('.showUserHrreferntId');
        
        if($(this).val().length==0){
            $container.empty().hide();
             $container.parent().find('.showNextDiv').hide();

              $(this).parent().parent().parent().next('tr').show();
        }else{
             $(this).parent().parent().parent().next('tr').hide();
        $container.parent().find('.showNextDiv').show();
        $container.empty().append('<div class="fieldLoader"></div>').show();
        $.post($action,function(data){
            $container.empty().append(data);
        });}
    });

    //profile reference show detail
    $('#DmdformProfileReferenceUserId').live('change',function(){
        $action=PathUser+'showUser/'+$(this).val();
        $container=$('.showProfileReferenceUserId');
        
        if($(this).val().length==0){
            $container.empty().hide();
             $container.parent().find('.showNextDiv').hide();

              $(this).parent().parent().parent().next('tr').show();
        }else{
             $(this).parent().parent().parent().next('tr').hide();
        $container.parent().find('.showNextDiv').show();
        $container.empty().append('<div class="fieldLoader"></div>').show();
        $.post($action,function(data){
            $container.empty().append(data);
        });}
    });

    //Filter Users
    $('.filterUsers').live('submit',function(){
        $action=$(this).attr('action');
        $f=$(this).serialize();
        $container=$('.popBox_container');
        $container.empty().append('<div class="fieldLoader"></div>')
        $.post($action,$f,function(data){
            $container.empty().append(data);
        });
        return false;
    });

    $('.acceptUser').live('click',function(){
        $id=$('#found').val();
        $list=$('#List').text();
        $('#'+$list).val($id);$('#'+$list).trigger('change');
        popBox.close();
        
    });

    //Filter Companiess
    $('.filterCompanies').live('submit',function(){
        $action=$(this).attr('action');
        $f=$(this).serialize();
        $container=$('.popBox_container');
        $container.empty().append('<div class="fieldLoader"></div>')
        $.post($action,$f,function(data){
            $container.empty().append(data);
        });
        return false;
    });

    $('.acceptCompany').live('click',function(){
        $id=$('#found').val();
        $list=$('.filterC a').attr('class');
        $('#'+$list).val($id);
        //alert($id);
        popBox.close();

    });
    
    //
    $('.selectCountry').live('change',function(){
            $('.selectCompany').empty().html('<option value>select country</option>');
             $('.selectSite').empty().html('<option value>select company</option>');
             $('.selectDepartment').empty().html('<option value>select site</option>');
             $('.compId').val('0');
        if($(this).val()>0){
            $(this).parent().parent().append('<div class="fieldLoader"></div>')
            path=PathComp+'getCompaniesForCountry/'+$(this).val();
            $.get(path,{},function(data){
                $('.selectCompany').html(data);
                $('.fieldLoader').remove();
            });
        }
    });
    $('.selectCompany').live('change',function(){
             $('.selectSite').empty().html('<option value>select company</option>');
             $('.selectDepartment').empty().html('<option value>select site</option>');
             $('.compId').val('0');
             //alert($(this).val().length);
        if($(this).val().length>0){
            $('.selectDepartment').empty().html('<option value>select site</option>');
            $(this).parent().parent().append('<div class="fieldLoader"></div>')
            path=PathComp+'getSitesForCompany/'+$(this).val();
            $.get(path,{},function(data){
                //alert(data);
                $('.selectSite').html(data);
                $('.fieldLoader').remove();
            });
       
        }
    });
    $('.selectSite').live('change',function(){
            $('.selectDepartment').empty().html('<option value>select site</option>');
             $('.compId').val('0');
        if($(this).val().length>0){
            $(this).parent().parent().append('<div class="fieldLoader"></div>')
            path=PathComp+'getDepartmentsForSite/'+$(this).val();
            $.get(path,{},function(data){
                $('.selectDepartment').html(data);
                $('.fieldLoader').remove();
            });  
        }
    });
    $('.selectDepartment').live('change',function(){
        $('.compId').val('0');
        if($(this).val().length>0){
            
            path=PathComp+'getCompanyId/'+$(this).val()+'/'+$('.selectSite').val()+'/'+$('.selectCompany').val()+'/'+$('.selectCountry').val();
            $.get(path,{},function(data){
               $('.compId').val(data);                
            });
        }
    });
/* JOB PROFILES*/

function checkCompatibilities(){
    //alert('ee');
    $j1id=$('#DmdformUserJobprofile1Id').val();
    $j2id=$('#DmdformUserJobprofile2Id').val();
    $j3id=$('#DmdformUserJobprofile3Id').val();
    $path='/alwpa/jobprofiles/checkCompatibility/';
    $txt='';
    //1 et 2
    if($j1id.length>0 && $j2id.length>0){
       
            $.ajax({
                async:false,
                url: $path+$j1id+'/'+$j2id ,
                success:function(data){                
                    if(data.length>0){
                       // alert(data);    
                        $txt='<p>Jobprofile 1 and Jobprofile 2 :'+data +'</p>';
                    }
                    }
            });
    }
    
    //2 et 3
    if($j3id.length>0 && $j2id.length>0){
            $.ajax({
                async:false,
                url: $path+$j2id+'/'+$j3id ,
                success:function(data){                
                    if(data.length>0){
                        $txt=$txt+'<p>'+'Jobprofile 2 and Jobprofile 3 :'+data+'</p>';
                    }
                    }
            });
    }
    //1 et 3
    if($j1id.length>0 && $j3id.length>0){

            $.ajax({
                async:false,
                url: $path+$j1id+'/'+$j3id,
                success:function(data){                
                    if(data.length>0){
                        $txt=$txt+'<p>Jobprofile 1 and Jobprofile 3 :'+data+'</p>';
                    }
                    }
            });
    }
    //alert($txt);
        if ($txt.length>0){
            $('#compCheck').empty().append($txt).show();
        }else{
            $('#compCheck').empty().hide();
        }
}

$('#DmdformUserJobprofile2Id').live('change',function(){checkCompatibilities();});
$('#DmdformUserJobprofile3Id').live('change',function(){checkCompatibilities();});
$('#DmdformUserJobprofile1Id').live('change',function(){checkCompatibilities();});
/* ******************** DEMAND FORM DETAILs ********************** */
    $('.formDetails').live('click',function(){
        $href=$(this).attr('href');
        $container=$(this).parent().next('div');
        if ($container.is(':hidden')){

        $container.empty().append('<div class="loader"></div>').slideDown();
        $.post($href,function(data){$container.empty().append(data);});
        }else{
            $container.slideUp('fast',function(){$container.empty();});
        }
        return false;
    });
   $('.formStatusChange').live('submit',function(){
       $('.popBox_container').empty().append('<div class="loader"></div>');
   });
   $('.hideMenu').live('click',function(){
        $('.filterForms').slideUp();
        $('.showMenu').show();
   });
   $('.showMenu').live('click',function(){
       $('.filterForms').slideDown();
       $(this).hide();
   });
});



var prmdform={
    nbSlide:0,
    nbCurrent:1,
    elemCurrent:null,
    elem: null,
    timer: null,


    init: function(elem){
        this.nbSlide = elem.find(".prmdf").length;
        this.nbCurrent=1;

        this.elem=elem;
        elem.find(".prmdf").hide();
        elem.find(".prmdf:first").show();
        this.elemCurrent=elem.find(".prmdf:first");
          this.elem.find(".nextPrmdf").live('click',function(){prmdform.Next();});
          this.elem.find(".prevPrmdf").click(function(){prmdform.Prev();});
         $('.formRub').click(
                function(){
                    $('.formRub').removeClass('active');
                    num=$(this).attr('href');
                    prmdform.gotoSlide(num);
                    $(this).addClass('active');
                    return false;
                }
            );
    },

    gotoSlide: function(num){
        var sens=-1;
        if(num==this.nbCurrent){return false;}       
        if(parseInt(num) >parseInt(this.nbCurrent)){sens=1;}else{sens=-1;}
        var cssDep={"left":sens*this.elem.width()};
        var cssFin={"left":-sens*(this.elem.width()+30)};
        this.elem.find("#prmdf"+num).show().css(cssDep);
        this.elem.find("#prmdf"+num).animate({"top":0,"left":0},500);
        this.elemCurrent.animate(cssFin,500);
        $('.formRub').removeClass('active');
        $("#rub"+num).addClass("active");
        this.nbCurrent=num;
        this.elemCurrent=this.elem.find("#prmdf"+num);
    },

    Next: function(){
        num=parseInt(this.nbCurrent)+1;
        if(num>this.nbSlide){num=1;}
        this.gotoSlide(num);
    },
    
    Prev: function(){
        num=parseInt(this.nbCurrent)-1;
        if(num<1){num=this.nbSlide;}
        this.gotoSlide(num);
    }


}







